#!/bin/bash 

NODE1_CONFDIR=/tmp/backup_htmf_conf
PATHENV=/etc/certificate-services.conf


echo "Welcome to $0, a tool to install EJBCA EXTRA"
LogFile="/tmp/smartcard2.0-extra-setup.$$"

runningid=`id -u`
if [ "x${runningid}" != "x0" ] ; then
    echo "must run as root eg: sudo $0"
    exit
fi

if [ -r ${PATHENV} ] ; then
    source ${PATHENV}
else
    echo "${PATHENV} missing"
    exit
fi


randompass() {
    MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    LENGTH="8"
    while [ "${n:=1}" -le "$LENGTH" ] ; do
        PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"
        let n+=1
    done
    echo "$PASS"
}


echo "verbose log messages is redirected to: sudo tail -f  ${LogFile}"
echo "Enter to continue, ctrl-c to abort"
echo
read a


echo "Running step: config input" 
### input ####
defmysqladminroot=root
echo
echo "We'll need your MySQL admin username to setup the database for you?"
echo -n "mysql-admin-root [${defmysqladminroot}]>"
read mysqladminroot 
if [ "x${mysqladminroot}" = "x" ] ; then
	mysqladminroot=${defmysqladminroot}
fi
    
defmysqladminpass=
echo
echo "We'll need your MySQL admin pass to setup the database for you?"
echo -n "mysql-admin-pass [${defmysqladminpass}]>"
read mysqladminpass
if [ "x${mysqladminpass}" = "x" ] ; then
        mysqladminpass=${defmysqladminpass}
fi
    
defmysqlserverhostname=localhost
echo
echo "What is the MySQL hostname?"
echo -n "mysql-serverhostname [${defmysqlserverhostname}]>"
read mysqlserverhostname
if [ "x${mysqlserverhostname}" = "x" ] ; then
        mysqlserverhostname=${defmysqlserverhostname}
fi
    
defmysqlextradbname=messages
echo
echo "What do you want the External RA db to be called(default is often very good)?"
echo -n "mysql-extra-dbname [${defmysqlextradbname}]>"
read mysqlextradbname
if [ "x${mysqlextradbname}" = "x" ] ; then
        mysqlextradbname=${defmysqlextradbname}
fi
    
defmysqlextrauser=ejbca
echo
echo "Select a MySQL username used to connect to the database from extra"
echo -n "mysql-extra-user [${defmysqlextrauser}]>"
read mysqlextrauser
if [ "x${mysqlextrauser}" = "x" ] ; then
        mysqlextrauser=${defmysqlextrauser}
fi
    
mysqlextrapass=`randompass`
    
defkeystorepath="/tmp/scep-ra-files/scepkeystore.p12"
echo
echo "Enter the path for the scepkeystore"
echo -n "scepkeystore-path [${defkeystorepath}]>"
read keystorepath
if [ "x${keystorepath}" = "x" ] ; then
    keystorepath=${defkeystorepath}
fi


defkeystorepass=foo123
echo
echo "Enter the password for the scepkeystore"
echo -n "scepkeystore-password [${defkeystorepass}]>"
read keystorepass
if [ "x${keystorepass}" = "x" ] ; then
    keystorepass=${defkeystorepass}
fi


defscepca=ServerCA
echo
echo "Enter the CA name (EJBCA shortname as seen in adminweb)"
echo -n "scepca [${defscepca}]>"
read scepca
if [ "x${scepca}" = "x" ] ; then
    scepca=${defscepca}
fi


defscepcp="CP_SSLServer"
echo
echo "Enter the Certificate Profile name (EJBCA name as seen in adminweb)"
echo -n "scepcp [${defscepcp}]>"
read scepcp
if [ "x${scepcp}" = "x" ] ; then
    scepcp=${defscepcp}
fi


defscepep="EEP_SSLServer"
echo
echo "Enter the End entity Profile name (EJBCA name as seen in adminweb)"
echo -n "scepep [${defscepep}]>"
read scepep
if [ "x${scepep}" = "x" ] ; then
    scepep=${defscepep}
fi


defsceppass="none"
echo
echo "If you like all SCEP Requests to be forced to use a password enter that here or press enter to use none"
echo -n "sceppass [${defsceppass}]>"
read sceppass
if [ "x${sceppass}" = "x" ] ; then
    scepep=${defsceppass}
fi

echo "Running step: config input: ok" 


StopJboss () {
    echo -n "Running step: Stoping jboss: "
    /etc/init.d/jboss stop      >> ${LogFile} 2>&1

    checkIfJbossIsRunning=`ps -ef | grep java | grep jboss | grep -v grep | awk '{print $2}' `
    if [ "x${checkIfJbossIsRunning}" != "x" ] ; then
        sleep 5
        kill -9 ${checkIfJbossIsRunning} >> ${LogFile} 2>&1
    fi       

    echo "ok"

}

ConfigureDatabase () {
    echo -n "Running step: setting up database: "
	# create mysql db

	# src/appserver/jboss/ramessage1-ds.xml

perl -pi -e "s#connection-url>jdbc:mysql://.*</connection-url#connection-url>jdbc:mysql://${mysqlserverhostname}/${mysqlextradbname}</connection-url#gio" ${EXTRA_HOME}/src/appserver/jboss/ramessage1-ds.xml
perl -pi -e "s#user-name>.*</user-name#user-name>${mysqlextrauser}</user-name#gio"     ${EXTRA_HOME}/src/appserver/jboss/ramessage1-ds.xml
perl -pi -e "s#password>.*</password#password>${mysqlextrapass}</password#gio"         ${EXTRA_HOME}/src/appserver/jboss/ramessage1-ds.xml


	   #mysql code conf + jar 	
	   #### creating mysql db ####
	
	echo 'show tables' | mysql --user=$mysqladminroot --password=$mysqladminpass $mysqlextradbname >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
	    echo
	    echo "database $mysqlextradbname does already exist, do you want to start fresh (I'll delete it and add a new ...)?"
	    echo -n "drop-old-db y/n [y]>"
	    read drop
	    if [ "x$drop" = "xy" -o "x$drop" = "xY" -o "x$drop" = "x" ] ; then
		mysqladmin drop --user=$mysqladminroot --password=$mysqladminpass $mysqlextradbname 
            else
		echo
		echo "ok, so now you need to sort this manually, then rerun me ( $0 )"
		exit 1
            fi
	    
	fi
	
	mysqladmin create --user=$mysqladminroot --password=$mysqladminpass $mysqlextradbname >> ${LogFile} 2>&1
	if [ $? -ne 0 ] ; then
	    echo "failed to create mysql database, you need to do it your self"
	    exit 2	
	fi
	
	#### creating mysql user ####
	
	echo "grant all privileges on ${mysqlextradbname}.* to ${mysqlextrauser}@${mysqlserverhostname} identified by '${mysqlextrapass}';" | mysql mysql --user=$mysqladminroot --password=$mysqladminpass >> ${LogFile} 2>&1
	if [ $? -ne 0 ] ; then
	    echo "failed to create mysql ejbca user , you need to do it your self"
	    exit 3
	fi
	
	echo "ok"
}

CopyP12FileForScepRA () {
	echo -n "Running step: configuring scep keystore: "
	# keystore/sceprakeystore.p12
	mkdir ${EXTRA_HOME}/keystore >> ${LogFile} 2>&1
	cp ${keystorepath} ${EXTRA_HOME}/keystore/sceprakeystore.p12 >> ${LogFile} 2>&1
	chmod 700 ${EXTRA_HOME}/keystore >> ${LogFile} 2>&1
	chmod 600 ${EXTRA_HOME}/keystore/* >> ${LogFile} 2>&1
	chown jboss.jboss -R ${EXTRA_HOME}/keystore/ >> ${LogFile} 2>&1
	echo "ok"
}

ConfigureScepProp () {
	echo -n "Running step: Configure SCEP props: "

	#Configure the SCEP RA Server in conf/scep.properties. Configure the certificate profile, end entity profile and CA settings to match the CA and profiles you will use for your SCEP certificates. Also configure the keyStorePassword to match the password on your sceprakeystore.p12 created before.
	#You can optionally configure the authPwd property if you want to authenticate SCEP messages based on a password in the request.

#scep.ra.keyStorePassword.1=foo123
perl -pi -e "s/.*scep.ra.keyStorePassword.1=foo123/scep.ra.keyStorePassword.1=${keystorepass}/gio" ${EXTRA_HOME}/conf/scep.properties

#scep.ra.defaultCA=ScepCA
perl -pi -e "s/.*scep.ra.defaultCA=ScepCA/scep.ra.defaultCA=${scepca}/gio" ${EXTRA_HOME}/conf/scep.properties
#scep.ra.entityProfile=EMPTY
perl -pi -e "s/.*scep.ra.entityProfile=EMPTY/scep.ra.entityProfile=${scepep}/gio" ${EXTRA_HOME}/conf/scep.properties
#scep.ra.certificateProfile=ENDUSER
perl -pi -e "s/.*scep.ra.certificateProfile=ENDUSER/scep.ra.certificateProfile=${scepcp}/gio" ${EXTRA_HOME}/conf/scep.properties
#scep.ra.authPwd=none
perl -pi -e "s/.*scep.ra.authPwd=none/scep.ra.authPwd=${sceppass}/gio" ${EXTRA_HOME}/conf/scep.properties


	echo "ok"

}

CopyMysqlJavaJarToJboss() {
	echo -n "Running step: adding mysql java driver to jboss: "
	cp ${MYSQLDRIVER} ${JBOSS_HOME}/server/default/lib >> ${LogFile} 2>&1
	${SMARTCARD20_HOME}/jboss-server-switch-log-level.pl INFO >> ${LogFile} 2>&1
	chown -R jboss.jboss ${JBOSS_HOME}/server/default/lib/*jar >> ${LogFile} 2>&1
	chmod 644 ${JBOSS_HOME}/server/default/lib/*jar >> ${LogFile} 2>&1
	echo "ok"

}

DeployScepRA(){
	echo -n "Running step: building/installing extra scep server: "
	cd ${EXTRA_HOME}
  	su -p -s /bin/sh jboss -c "cd ${EXTRA_HOME} ; ant deployscepraserver"  >> ${LogFile} 2>&1
	if [ $? -eq 0 ] ; then
		echo "ok"
	else
		echo
		echo "FAILED: deployscepraserver failed"
		exit 5
	fi

}

StartJboss () {
    echo -n "Running step: Starting jboss: "
    /etc/init.d/jboss start     >> ${LogFile} 2>&1
    echo "ok"

}

# main:

StopJboss
ConfigureDatabase
CopyP12FileForScepRA
ConfigureScepProp
CopyMysqlJavaJarToJboss
DeployScepRA
StartJboss

